<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author XPF
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'sports:sportsTemplateConfig:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="90%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #sportsIndexTemplateRelationList>
        <a-button
          class="mt-2"
          @click="handleSportsIndexTemplateRelationAdd"
          v-auth="'sports:sportsTemplateConfig:edit'"
        >
          {{ t('添加指标') }}
        </a-button>
        <BasicTable @register="registerSportsIndexTemplateRelationTable" rowKey="id">
          <template #testStatusDisplay="{ column, record }">
            <a-button @click="handletestStatusDisplay(record)">
              {{ record.testStatusDisplay == 0 ? '显示' : '否' }}
            </a-button>
          </template>
        </BasicTable>
      </template>
    </BasicForm>
  </BasicDrawer>
  <Modal @register="registerModal" @success="handleSuccess" @save="handleSave" />
</template>
<script lang="ts">
export default defineComponent({
  name: 'ViewsSportsSportsTemplateConfigForm',
});
</script>
<script lang="ts" setup>
import { defineComponent, ref, computed } from 'vue';
import { useI18n } from '/@/hooks/web/useI18n';
import { useMessage } from '/@/hooks/web/useMessage';
import { router } from '/@/router';
import { Icon } from '/@/components/Icon';
import { BasicForm, FormSchema, useForm } from '/@/components/Form';
import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
import { useModal } from '/@/components/Modal';
import {
  SportsTemplateConfig,
  sportsTemplateConfigSave,
  sportsTemplateConfigForm,
  sportsTemplateConfigListData,
} from '/@/api/sports/sportsTemplateConfig';
import Modal from './modal.vue';
import { any } from 'vue-types';
import { up } from 'inquirer/lib/utils/readline';
import { update } from 'lodash';
import { sportsTotalGradeRuleListData } from '/@/api/sports/sportsTotalGradeRule';
const emit = defineEmits(['success', 'register']);
const { t } = useI18n('sports.sportsTemplateConfig');
const { showMessage } = useMessage();
const record = ref<SportsTemplateConfig>({} as SportsTemplateConfig);
const getTitle = computed(() => ({
  icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
  value: record.value.isNewRecord ? t('新增体测模板配置') : t('编辑体测模板配置'),
}));
let grade;
let sex;
const inputFormSchemas: FormSchema[] = [
  {
    label: t('适配年级'),
    field: 'adaptGrade',
    component: 'Select',
    componentProps: {
      dictType: 'vke_grade',
      allowClear: true,
      onChange: (e: ChangeEvent) => {
        grade = e;
        RelationTableReload();
      },
    },
  },
  {
    label: t('性别'),
    field: 'adaptSex',
    component:'Select',
    componentProps: {
      dictType: 'sports_user_sex',
      allowClear: true,
      onChange: (e: ChangeEvent) => {
        sex = e;
        RelationTableReload();
      },
    }
  },
  {
    label: t('指标'),
    field: 'sportsIndexTemplateRelationList',
    component: 'Input',
    colProps: { lg: 24, md: 24 },
    slot: 'sportsIndexTemplateRelationList',
  },
];
let testStatusDisplay = true;
const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
  labelWidth: 200,
  schemas: inputFormSchemas,
  baseColProps: { lg: 24, md: 24 },
});

const tableColumns: BasicColumn[] = [
  {
    title: t('指标项'),
    dataIndex: 'indexName',
    width: 130,
    align: 'left',
  },
  {
    title: t('年级'),
    dataIndex: 'adaptGrade',
    width: 130,
    align: 'left',
    dictType: 'vke_grade',
  },
  {
    title: t('权重'),
    dataIndex: 'weight',
    width: 130,
    align: 'left',
  },
  {
    title: t('测试状态'),
    dataIndex: 'testStatusDisplay',
    width: 130,
    align: 'left',
    editComponent: 'Checkbox',
    // dictType: 'sys_yes_no',
    slots: { customRender: 'testStatusDisplay' },
  },
];

const actionColumn: BasicColumn = {
  width: 160,
  actions: (record: Recordable) => [
    {
      label: t('上移'),
      onClick: upying.bind(this, record, record.id),
      // auth: 'sports:sportsTemplateConfig:edit',
    },
    {
      label: t('下移'),
      onClick: preview.bind(this, record, record.id),

      auth: 'sports:sportsTemplateConfig:edit',
    },
    {
      icon: 'ant-design:delete-outlined',
      color: 'error',
      popConfirm: {
        title: '是否确认删除',
        confirm: handleSportsIndexTemplateRelationDelete.bind(this, record),
      },
      auth: 'sports:sportsTemplateConfig:edit',
    },
  ],
};
const [
  registerSportsIndexTemplateRelationTable,
  { reload: RelationTableReload, setTableData, deleteTableDataRecord },
] = useTable({
  columns: tableColumns,
  dataSource: record.sportsIndexTemplateRelationList,
  actionColumn: actionColumn,
  canResize: true,
  loading: false,
  immediate: false,
});
const [registerModal, { openModal }] = useModal();
function handleSportsIndexTemplateRelationAdd() {
  let arr = []
  sportsIndexTemplateRelationList.forEach((item)=>{
    console.log(item);
    arr.push(item.indexId)
  })
  openModal(true, { adaptGrade: grade,adaptSex:sex,arr });
}
let sportsIndexTemplateRelationList;

function handleSportsIndexTemplateRelationDelete(record: Recordable) {
  console.log(record);
  deleteTableDataRecord(record);
  handleSuccess();
}
let configId;
const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  resetFields();
  setDrawerProps({ loading: true });
  configId = data.configId;
  const res = await sportsTemplateConfigForm(data);
  record.value = (res.sportsTemplateConfig || {}) as SportsTemplateConfig;
  record.value.__t = new Date().getTime();
  if (!record.value.isNewRecord) {
    sportsIndexTemplateRelationList = [];
    let result = await sportsTemplateConfigListData(data);
    result.list[0].sportsIndexTemplateRelationList.forEach((item, index) => {
      sportsIndexTemplateRelationList.push({
        id: index,
        indexName: item.indexName,
        indexId: item.indexId,
        adaptGrade: result.list[0].adaptGrade,
        weight: (item.weight || item.weight == 0)? item.weight + '%' : '--',
        testStatusDisplay: (item.testStatusDisplay = item.testStatusDisplay
          ? item.testStatusDisplay
          : '0'),
      });
    });
    grade = data.adaptGrade;
  } else {
    sportsIndexTemplateRelationList = [];
    setTableData(sportsIndexTemplateRelationList);
  }
  setTableData(sportsIndexTemplateRelationList);
  setFieldsValue(record.value);
  setDrawerProps({ loading: false });
});

const upying = function (sorts, index) {
  if (index <= 0) {
    showMessage('已经是第一条了');
  } else {
    let upData = sportsIndexTemplateRelationList[index - 1];
    deleteTableDataRecord(upData);
    sportsIndexTemplateRelationList.splice(index, 0, upData);
    sorts.id -= 1;
    upData.id += 1;
  }
};
const preview = function (sorts, index) {
  if (index >= sportsIndexTemplateRelationList.length - 1) {
    showMessage('已经是最后一条了');
  } else {
    let upData = sportsIndexTemplateRelationList[index + 1];
    deleteTableDataRecord(upData);
    sportsIndexTemplateRelationList.splice(index, 0, upData);
    sorts.id += 1;
    upData.id -= 1;
  }
};
function handletestStatusDisplay(status) {
  if (status.testStatusDisplay == 1) {
    status.testStatusDisplay = 0;
  } else {
    status.testStatusDisplay = 1;
  }
}
async function handleSubmit() {
  try {
    const data = await validate();
    setDrawerProps({ confirmLoading: true });
    const params: any = {
      isNewRecord: record.value.isNewRecord,
      configId: record.value.configId,
    };
    let arr = <any>[];
    sportsIndexTemplateRelationList.forEach((item, index) => {
      arr.push({
        indexId: item.indexId,
        sort: index + 1,
        testStatusDisplay: item.testStatusDisplay,
      });
    });
    data.sportsIndexTemplateRelationList = arr;
    const res = await sportsTemplateConfigSave(params, data);
    showMessage(res.message);
    setTimeout(closeDrawer);
    emit('success', data);
    setTableData([]);
    sportsIndexTemplateRelationList = [];
  } catch (error: any) {
    if (error && error.errorFields) {
      showMessage(t('您填写的信息有误，请根据提示修正。'));
    }
    console.log('error', error);
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}
function handleSuccess() {
  RelationTableReload();
}
function handleSave(options) {
  sportsIndexTemplateRelationList = options;
  setTableData(options);
  RelationTableReload();
}
</script>
